package cn.iocoder.yudao.framework.push.core.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.mapstruct.ap.shaded.freemarker.template.utility.StringUtil;

import java.util.*;

@Slf4j
public class PushUtil {

    private static class SingletonHolder {
        private static final PushUtil INSTANCE = new PushUtil();
    }

    private PushUtil() {
        // 私有构造函数
    }


    private final int batchSize = 1000; // 每组的大小
    public static PushUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }
    public  String push(String pushUrl, List<String> cids, String payload){
//        String s = HttpUtil.post(pushUrl, payload);
        if (Objects.isNull(payload)){
            payload = "";
        }
        if(cids!=null && cids.size()>batchSize){
            List<List<String>> lists = regroupCids(cids);
            for (List<String> list : lists) {
                JSONObject obj = new JSONObject();
                obj.set("clientIds",list);
                obj.set("payload",payload);

                String response =  HttpUtil.createPost(pushUrl)
                        .contentType("application/json")
                        .body(obj.toString()).execute().body();
                log.info("推送 cid {} payload {} 结果为 {}",cids,payload,response);
            }
        }else{
            JSONObject obj = new JSONObject();
            obj.set("clientIds",cids);
            obj.set("payload",payload);

            String response =  HttpUtil.createPost(pushUrl)
                    .contentType("application/json")
                    .body(obj.toString()).execute().body();
            log.info("推送 cid {} payload {} 结果为 {}",cids,payload,response);
        }


        return "OK";
    }

//    https://zh.uniapp.dcloud.io/uniCloud/uni-cloud-push/api.html
//    基于uni.getPushClientId获取的客户端推送标识，指定接收消息的设备。
//    支持多个以数组的形式指定多个设备，如["cid-1","cid-2"]，数组长度不大于1000
    public List<List<String>> regroupCids(List<String> cids){



        int totalSize = cids.size(); // 列表的总大小
        int groupCount = (int) Math.ceil((double) totalSize / batchSize); // 计算组的数量

        List<List<String>> groupedLists = new ArrayList<>(); // 存储重新组织后的列表

        for (int i = 0; i < groupCount; i++) {
            int startIndex = i * batchSize;
            int endIndex = Math.min((i + 1) * batchSize, totalSize);

            List<String> group = cids.subList(startIndex, endIndex);
            groupedLists.add(group);
        }

// 打印重新组织后的列表

        return groupedLists;
    }



}
